using System.Runtime.Serialization;
using System.Text.Json;

namespace MultiAgentsShared;

public abstract class SerializableObjectBase
{
    private static readonly JsonSerializerOptions defaultOptions = new()
    {
        WriteIndented = true,
        IncludeFields = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };

    protected SerializableObjectBase() { }
    public string ConvertToJson(JsonSerializerOptions? options = null)
    {
        try
        {
            return JsonSerializer.Serialize(this, GetType(), options ?? defaultOptions);
        }
        catch (Exception ex)
        {
            throw new SerializationException("Failed to serialize object to JSON.", ex);
        }
    }

    public static string ConvertToJson<T>(T data, JsonSerializerOptions? options = null)
    {
        try
        {
            return JsonSerializer.Serialize(data, typeof(T), options ?? defaultOptions);
        }
        catch (Exception ex)
        {
            throw new SerializationException("Failed to serialize object to JSON.", ex);
        }
    }

    public static T FromJson<T>(string json, JsonSerializerOptions? options = null) where T : class, new()
    {
        try
        {
            return JsonSerializer.Deserialize<T>(json, options ?? defaultOptions) ?? new T();
        }
        catch (Exception ex)
        {
            throw new SerializationException("Failed to deserialize JSON to object.", ex);
        }
    }
}
